<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-select :filter-method="stationNamehandleFilter" clearable filterable remote size="mini"
                        style="width:220px" v-model="find_data.stationName" class="m-2" placeholder="请选择站点名称">
                        <el-option v-for="item in getStationList_Data" :key="item.stationName" :label="item.stationName"
                            :value="item.stationName">
                            <span style="float: left">{{ item.stationName }}</span>

                        </el-option>

                    </el-select>

                    <el-select v-model="find_data.seats" :placeholder="'请填写座位数'"
                        style="width: 130px;margin-left: 10px;">
                        <el-option label="5座" value="5" />
                        <el-option label="7座" value="7" />
                        <el-option label="9座" value="9" />
                        <el-option label="12座" value="12" />
                        <el-option label="14座" value="14" />
                        <el-option label="17座" value="17" />
                        <el-option label="39座" value="39" />
                        <el-option label="49座" value="49" />
                        <el-option label="55座" value="55" />
                    </el-select>

                    <el-select clearable v-model="find_data.staffState" :placeholder="'员工入职状态'"
                        style="width: 130px;margin-left: 10px;">
                        <el-option label="正式" value="NORMAL"></el-option>
                        <el-option label="试用" value="TRY"></el-option>
                        <el-option label="挂靠" value="DEPEND"></el-option>
                        <el-option label="兼职" value="SOMETIME"></el-option>
                        <el-option label="离职" value="LEAVE"></el-option>
                    </el-select>

                    <el-date-picker :default-time="defaultTime" style="margin-left: 10px;width: 340px;"
                        v-model="timeTypeTime" @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">新增</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%" row-key="id"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">


                            <template v-if="item.field == 'staffState'" #="{ row, column, $index }">
                                <span>{{ row.staffState == 'NORMAL' ? '正式' : row.staffState == 'SOMETIME' ? '兼职' :
                                    row.staffState
                                        == 'DEPEND' ? '挂靠' : row.staffState == 'TRY' ? '试用' : row.staffState == 'LEAVE' ?
                                            '离职'
                                    :''}}</span>


                            </template>
                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="35%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="130px" label-suffix="：">
                <el-form-item label="站点名称">
                    <el-select :filter-method="stationNamehandleFilter" multiple collapse-tags  clearable filterable remote size="mini"
                        style="width:300px" v-model="add_data.stationNames" class="m-2" placeholder="请选择站点名称">
                        <el-option v-for="item in getStationList_Data" :key="item.stationName" :label="item.stationName"
                            :value="item.stationName">
                            <span style="float: left">{{ item.stationName }}</span>

                        </el-option>

                    </el-select>
                </el-form-item>
                <el-form-item label="员工入职状态">
                    <el-select clearable v-model="add_data.staffState" :placeholder="'员工入职状态'" style="width: 300px;">
                        <el-option :label="'正式'" :value="'NORMAL'"></el-option>
                        <el-option :label="'兼职'" :value="'SOMETIME'"></el-option>
                        <el-option :label="'挂靠'" :value="'DEPEND'"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="最小车型">
                    <el-select v-model="add_data.minSeats" :placeholder="'请填写最小车型'" style="width: 300px;">
                        <el-option label="5座" value="5" />
                        <el-option label="7座" value="7" />
                        <el-option label="9座" value="9" />
                        <el-option label="12座" value="12" />
                        <el-option label="14座" value="14" />
                        <el-option label="17座" value="17" />
                        <el-option label="39座" value="39" />
                        <el-option label="49座" value="49" />
                        <el-option label="55座" value="55" />
                    </el-select>
                </el-form-item>
                <el-form-item label="最大车型">
                    <el-select v-model="add_data.maxSeats" :placeholder="'请填写最大车型'" style="width: 300px;">
                        <el-option label="5座" value="5" />
                        <el-option label="7座" value="7" />
                        <el-option label="9座" value="9" />
                        <el-option label="12座" value="12" />
                        <el-option label="14座" value="14" />
                        <el-option label="17座" value="17" />
                        <el-option label="39座" value="39" />
                        <el-option label="49座" value="49" />
                        <el-option label="55座" value="55" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工资">
                    <el-input type="number" style="width:300px" v-model="add_data.salaryPrice" placeholder="请填写工资">
                        <template #append>元</template></el-input>
                </el-form-item>
                <el-form-item label="超范围补助">
                    <el-input type="number" style="width:300px" v-model="add_data.moreDistanceSalary"
                        placeholder="请填写超范围补助">
                        <template #append>元/公里</template></el-input>
                </el-form-item>
            </el-form>


            <el-button @click="ok_btn" style="margin-left:25vw" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import {
    line2treeData

} from '@/utils/common.js'

import {
    adupPrivateSet, getPrivateSetList, adupSalarySet, delSalarySet, findSalarySetList, getStationListPages

} from '@/api/system_management.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import CircularJSON from 'circular-json'
onMounted(async () => {


    getPrivateSetList({
        find: '工资设置',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })

    getStationListPages({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        stationTypes: ['TRAIN', 'AIRPORT', 'BUS'],
    }).then(res => {
        if (res.code == 1) {
            getStationList_Data.value = res.data.list
            getStationList_Data2.value = res.data.list
        }
    })



    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

        }
    })





    await list_api()

})

//#region 表格数据处理
const table_data_list = reactive([
    { label: '站点名称', field: 'stationName', width: '', off: true },
    { label: '员工入职状态', field: 'staffState', width: '', off: true },
    { label: '最小车型', field: 'minSeats', width: '', off: true },
    { label: '最大车型', field: 'maxSeats', width: '', off: true },
    { label: '工资', field: 'salaryPrice', width: '', off: true },
    { label: '超范围补助【元/公里】', field: 'moreDistanceSalary', width: '', off: true },
    { label: '添加时间', field: 'addTime', width: '', off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '工资设置',
        tbNum: "salary_setting",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 分页列表
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const timeTypeTime = ref([])
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}

const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 200,
    },
    seats: '',
    etime: '',
    staffState: '',
    stationName: '',
    stime: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    findSalarySetList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total

    })
}
//#endregion

//#region 添加

const stationNamehandleFilter = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = getStationList_Data2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            getStationList_Data.value = results
        } else {
            getStationList_Data.value = []
        }
    } else {
        getStationList_Data.value = getStationList_Data2.value
    }
}
const getStationList_Data = ref([])
const getStationList_Data2 = ref([])
const add_off = ref(false)
const title = ref('添加工资设置')

const add_data = reactive({

    id: '',
    maxSeats: "",
    minSeats: "",
    moreDistanceSalary: "",
    salaryPrice: "",
    staffState: "",
    stationNames: [],
})
const add_btn = () => {
    title.value = '添加工资设置'

    add_data.id = ''
    add_data.maxSeats = ''
    add_data.minSeats = ''
    add_data.moreDistanceSalary = ''
    add_data.salaryPrice = ''
    add_data.staffState = ''
    add_data.stationNames = []


    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改工资设置'
    add_data.maxSeats = table_list.value[0].maxSeats
    add_data.minSeats = table_list.value[0].minSeats
    add_data.moreDistanceSalary = table_list.value[0].moreDistanceSalary
    add_data.salaryPrice = table_list.value[0].salaryPrice
    add_data.staffState = table_list.value[0].staffState
    add_data.stationNames =[table_list.value[0].stationName]
    add_data.typeName = table_list.value[0].typeName
    add_data.id = table_list.value[0].id

    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {




    if (title.value == '添加工资设置') {

        adupSalarySet(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {

        adupSalarySet(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认删除`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delSalarySet({
                id: table_list.value[0].id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {

    list_api()
}


</script>

<style scoped lang='scss'>
.paddingLeft {
    padding-left: 24px;
}

.paddingLeft_3 {
    padding-left: 48px;
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
